package cn.ml.mybatisdemo.filter;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.*;
import java.io.IOException;
import java.io.Reader;

public class OpenSessionInViewFilter implements Filter {
    private SqlSessionFactory factory;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        try {
            //从web.xml中获取path路径
            String filePath = filterConfig.getInitParameter("path");
            Reader reader = Resources.getResourceAsReader(filePath);
            factory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        SqlSession sqlSession = factory.openSession();
        servletRequest.setAttribute("sqlSession",sqlSession);
        filterChain.doFilter(servletRequest,servletResponse); //调用servlet中doGet/doPost方法
        //servlet做完增删改查，不用提交,做完被filter拦截后交给filter来提交
        sqlSession.commit();

    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
